<!-- 使用 JavaScript 编写代码实现一个表单验证，要求检查输入的电子邮件格式是否正确，当格式不正确时在表单旁边显示红色的错误提示信息。 -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF - 8">
    <title>Form Validation</title>
    <style>
      .error {
            color: red;
        }
    </style>
</head>

<body>
    <form>
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email"><br>
        <span id="emailError" class="error"></span>
        <label for="phone">Phone Number:</label><br>
        <input type="text" id="phone" name="phone"><br>
        <span id="phoneError" class="error"></span>
        <input type="submit" value="Submit">
    </form>
    <script>
        // 获取表单元素和错误提示元素
        const emailInput = document.getElementById('email');
        const emailError = document.getElementById('emailError');
        const phoneInput = document.getElementById('phone');
        const phoneError = document.getElementById('phoneError');

        // 为表单添加提交事件监听器
        document.querySelector('form').addEventListener('submit', function (event) {
            const emailValue = emailInput.value;
            const emailRegex = /^[a-zA - Z0 - 9_.+-]+@[a-zA - Z0 - 9 -]+\.[a-zA - Z0 - 9 -.]+$/;
            if (!emailRegex.test(emailValue)) {
                emailError.textContent = 'Invalid email format';
                event.preventDefault();
            } else {
                emailError.textContent = '';
            }

            const phoneValue = phoneInput.value;
            const phoneRegex = /^1[3 - 9]\d{9}$/;
            if (!phoneRegex.test(phoneValue)) {
                phoneError.textContent = 'Invalid phone number format';
                event.preventDefault();
            } else {
                phoneError.textContent = '';
            }
        });
    </script>
</body>

</html>